﻿using BrnMall.Core;
using BrnMall.Manager.Domain.User;
using BrnMall.Manager.Manager.Order;
using BrnMall.Manager.Manager.User;
using BrnMall.Services;
using BrnMall.Web.Framework;
using BrnMall.Web.StoreAdmin.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web.Mvc;

namespace BrnMall.Web.StoreAdmin.controllers
{
    public partial class CashController : BaseStoreAdminController
    {
        /// <summary>
        /// 财务统计查询
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public ActionResult ReportSearch(string accountName = "", string startTime = "", string endTime = "")
        {
            accountName = accountName.Trim();
            startTime = string.IsNullOrEmpty(startTime) ? DateTime.Now.AddMonths(-3).ToString("yyyy-MM-dd") : startTime;
            endTime = string.IsNullOrEmpty(endTime) ? DateTime.Now.ToString("yyyy-MM-dd") : endTime;

            var totalCash = CashRecordManager.GetTotalMoney(WorkContext.StoreId, 0, accountName, startTime, endTime);
            var totalOrder = OrderManager.GetTotalMoney(WorkContext.StoreId, 0, accountName, startTime, endTime);

            var model = new ReportSearchModel()
            {
                AccountName = accountName,
                StartTime = startTime,
                EndTime = endTime
            };


            //充值金额
            model.CashMoney = totalCash["TimeInMoney"];
            //订单在线付款金额
            model.SurplusMoney = totalOrder.SurplusMoney;
            model.CouponMoney = totalOrder.CouponMoney;
            model.FullCut = totalOrder.FullCut;
            model.PayCash = totalOrder.PayCash;
            model.PayCreditMoney = totalOrder.PayCreditMoney;
            //总收入
            model.TotalInMoney = model.CashMoney + model.SurplusMoney;
            //总消费
            model.TotalOutMoney = totalOrder.OrderAmount;


            ////充值金额
            //model.CashMoney = totalCash["TimeInMoney"];
            ////订单在线付款金额
            //model.OnLineMoney = totalOrder["SurplusMoney"];
            ////总收入
            //model.InMoney = model.CashMoney + model.OnLineMoney;
            ////总消费
            //model.OutMoney = totalOrder["OrderAmount"];
            return View(model);
        }

        /// <summary>
        /// 会员交易记录
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="accountName">会员昵称</param>
        /// <param name="direction">类型(1收入，2支出)</param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ActionResult CashRecordList(int uid = 0, string accountName = "", int direction = 0, string startTime = "", string endTime = "", int pageNumber = 1, int pageSize = 15)
        {
            accountName = accountName.Trim();
            startTime = string.IsNullOrEmpty(startTime) ? DateTime.Now.AddMonths(-3).ToString("yyyy-MM-dd") : startTime;
            endTime = string.IsNullOrEmpty(endTime) ? DateTime.Now.ToString("yyyy-MM-dd") : endTime;

            if (!SecureHelper.IsSafeSqlString(accountName))
                return PromptView("昵称里含非法关键词，请删除");

            var dbList = CashRecordManager.GetListPage(WorkContext.StoreId, uid, accountName, direction, startTime, endTime, pageNumber, pageSize);
            var list = FillUser(dbList.Items);

            //时间段内总收入,总支出
            var dic = CashRecordManager.GetTotalMoney(WorkContext.StoreId, uid, accountName, startTime, endTime);

            var model = new CashRecordListModel()
            {
                uid = uid,
                StartTime = startTime,
                EndTime = endTime,
                List = list,
                PageModel = new PageModel(pageSize, pageNumber, (int)dbList.TotalItems),
                Direction = direction,
                TimeInMoney = dic["TimeInMoney"],
                TimeOutMoney = dic["TimeOutMoney"]
            };

            return View(model);
        }


        IList<CashRecordView> FillUser(List<CashRecord> list)
        {
            var recordList = new List<CashRecordView>();
            //会员ID
            StringBuilder sbId = new StringBuilder();
            list.ForEach(x => sbId.AppendFormat(",{0}", x.Uid));

            if (sbId.Length > 0) sbId.Remove(0, 1);

            //会员列表
            var connection = string.Format("bma_users.uid in({0})", sbId.ToString());
            var userList = sbId.Length < 1 ? new DataTable() : Users.GetUserList(list.Count, 1, connection);

            foreach (var item in list)
            {
                var info = new CashRecordView() { StoreId = item.StoreId, Uid = item.Uid, Amount = item.Amount, GiveAmount = item.GiveAmount, Balance = item.Balance, Direction = item.Direction, CreateTime = item.CreateTime, remark = item.remark };
                foreach (DataRow user in userList.Rows)
                {
                    if (Convert.ToInt32(user["uid"]) == item.Uid)
                    {
                        info.AccountName = Convert.ToString(user["NickName"]);
                        break;
                    }
                }
                recordList.Add(info);
            }
            return recordList;
        }
    }
}